package com.gamelife.web.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUploadUtils {

    //保存在window服务器路径
    public static final String UPLOAD_PATH = "D:/cms/resources/";
    //保存在linux服务器路径 
    //private static final String UPLOAD_PATH = "/usr/local/picture/";

    //文件类型
    private final static String VIDEO_TYPE_AVI = "avi";
    private final static String VIDEO_TYPE_MP4 = "mp4";
    private final static String VIDEO_TYPE_WMV = "wmv";
    private final static String VIDEO_TYPE_MPG = "mpg";
    private final static String VIDEO_TYPE_MPEG = "mpeg";
    private final static String VIDEO_TYPE_MOV = "mov";

	//上传文件
    public static String upload(MultipartFile file) throws Exception {
        String fileOriginName = file.getOriginalFilename();
        DateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-","");
        String fileName = String.format("%s-%s.%s", fmt.format(new Date()),
                uuid, getSuffix(fileOriginName));
        File dest = new File(UPLOAD_PATH + fileName);
        // 如果路径不存在创建路径
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("上传图片失败");
        }
        //将此路径保存在数据库中 访问时通过 http://ip:port/filePath/ + fileName访问
        return "/upload/" + fileName;
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

}
